import base64
import json

import faker
from locust import FastHttpUser, task, between, run_single_user, constant, events, tag,constant_pacing,User

index_cookie = 2000
def get_cookie():
    global index_cookie
    index_cookie += 1
    l = []
    with open('../cookies.txt', mode='r', encoding='utf8') as f:
        for account in f:
            l.append(account.strip())
        return str(l[index_cookie])

def enconde_bs64(data):
    data = json.dumps(data)
    encode64 = base64.b64encode(data.encode('utf-8'))
    return encode64.decode('utf-8')

def decode64_str(data):
    decode64 = base64.b64decode(data)
    decode64_str = decode64.decode('utf-8')
    return decode64_str


class HearingAidScene(FastHttpUser):
    host = "https://www.retone-hearing.fit"
    wait_time = constant(1)
    # abstract = True
    fake = faker.Faker()
    cookie = get_cookie()
    def on_start(self):
        numbers_of_user = False
        if numbers_of_user == True:
            self.header = {"Cookie": f"hearingaid_user={get_cookie()}",
                           "Content-Type": "application/json"}
        else:
            self.header = {"Cookie": f"hearingaid_user={self.cookie}",
                           "Content-Type": "application/json"}
    #
    # @task
    # @tag
    # def add_scene(self):


    @task
    @tag('scene')
    def scene(self):
        """
        新增 -> 查询 -> 删除
        """
        # 查询所有场景,使用和为使用的
        get_scene_url = '/platformRetoneFit/api/hearingAidScene/needAppUserAuth/responseEncode/requestDecode/getAllHearingAidSceneSupportSceneUse'
        scene_id_list = []
        with self.rest('post', get_scene_url, headers=self.header) as resp:
            if resp.status_code != 200 or (resp.js['data'] is None and resp.js['description'] is not None):
                resp.failure(f"===错误返回status_code={resp.status_code}:resp_text={resp.js}===")
            else:
                try:
                    unuseSceneList = json.loads(decode64_str(resp.js['data']))['unuseSceneList']
                    # print(unuseSceneList)
                    for scene in unuseSceneList:
                        if scene['sceneName'] not in ['室内', '户外', '餐厅', '马路', '定向聚焦']:
                            scene_id_list.append(scene['hearingAidSceneId'])
                    
                except UnboundLocalError as JsonTypError:
                    resp.failure(f'{JsonTypError}场景为空')
                except TypeError as nodata:
                    resp.failure(f'场景为空:{nodata}')
        # print(len(scene_id_list))
        if len(scene_id_list)>=0 and len(scene_id_list) <=5:
            add_scene_url = '/platformRetoneFit/api/hearingAidScene/needAppUserAuth/responseEncode/requestDecode/addHearingAidScene'
            data = {
                "sceneName": self.fake.street_name(),
                "enableLocation": False,
                "backgroundPicture": "TEST_PICTURE",
                "icon": "ICON_PICTURE",
                "enableStudy": False
            }
            with self.rest('post', add_scene_url, data=enconde_bs64(data), headers=self.header) as resp:
                if resp.status_code != 200 or (resp.js['data'] is None and resp.js['description'] is not None):
                    resp.failure(f"===错误返回status_code={resp.status_code}:resp_text={resp.js}===")
                else:
                    _ = json.loads(decode64_str(resp.json()['data']))
                    self.add_id = _.get('hearingAidSceneId')
                    resp.success()
            # 修改场景
            modify_url = '/platformRetoneFit//api/hearingAidScene/needAppUserAuth/responseEncode/requestDecode/modifyHearingAidScene'
            # print(self.add_id)
            data = {
                    "hearingAidSceneId": str(self.add_id,),
                    "sceneName": str(self.fake.street_name()),
                    "enableLocation": True,
                    "longitude": str(self.fake.longitude()),
                    "latitude":  str(self.fake.latitude()),
                    "denoise": 3,
                    "leftEarEqualizer": {
                        "volume": 5,
                        "lowPitch": 3,
                        "middlePitch": 2,
                        "highPitch": 1
                    },
                    "rightEarEqualizer": {
                        "volume": 5,
                        "lowPitch": 3,
                        "middlePitch": 2,
                        "highPitch": 1
                    }
                }
            with self.rest('post', modify_url, data=enconde_bs64(data), headers=self.header) as resp:
                if resp.status_code != 200 or (resp.js['data'] is None and resp.js['description'] is not None):
                    resp.failure(f"===错误返回status_code={resp.status_code}:resp_text={resp.js}===")
                else:
                    resp.success()

            # 更新为场景为使用中
            update_scene_url = '/platformRetoneFit/api/hearingAidScene/needAppUserAuth/responseEncode/requestDecode/updateAllUseHearingAidScene'
            data = {
                "useSceneIdList":[self.add_id]
            }

            with self.rest('post', update_scene_url, data=enconde_bs64(data), headers=self.header) as resp:
                if resp.status_code != 200 or (resp.js['data'] is None and resp.js['description'] is not None):
                    resp.failure(f"===错误返回status_code={resp.status_code}:resp_text={resp.js}===")
                else:
                    resp.success()
            # 查询使用中的场景
            url = '/platformRetoneFit/api/hearingAidScene/needAppUserAuth/responseEncode/requestDecode/getAllUseHearingAidScene'
            with self.rest('post', url, headers=self.header) as resp:
                if resp.status_code != 200 or (resp.js['data'] is None and resp.js['description'] is not None):
                    resp.failure(f"===错误返回status_code={resp.status_code}:resp_text={resp.js}===")
                else:
                    _ = json.loads(decode64_str(resp.json()['data']))
                    self.using_id = []
                    for id in _:
                        self.using_id.append(id['hearingAidSceneId'])
                    resp.success()
        else:
            # 删除场景
            del_url = '/platformRetoneFit//api/hearingAidScene/needAppUserAuth/responseEncode/requestDecode/batchDeleteHearingAidScene'
            data = {
                'hearingAidSceneIdList': scene_id_list
            }
            # print(scene_id_list)
            with self.rest('post', del_url, data=enconde_bs64(data), headers=self.header) as resp:
                if resp.status_code != 200 or (resp.js['data'] is None and resp.js['description'] is not None):
                    resp.failure(f"===错误返回status_code={resp.status_code}:resp_text={resp.js}===")
                else:
                    resp.success()

    @task
    @tag('get_all_scene')
    def get_all_scene(self):
        get_scene_url = '/platformRetoneFit/api/hearingAidScene/needAppUserAuth/responseEncode/requestDecode/getAllHearingAidSceneSupportSceneUse'
        with self.rest('post', get_scene_url, headers=self.header) as resp:
            self.scene_id_list = []
            try:
                if resp.status_code > 400 or (resp.js['data'] is None and resp.js['description'] is not None):
                    resp.failure(f'错误返回{resp.status_code}, resp.txt={resp.text}')
                else:
                    unuseSceneList = json.loads(decode64_str(resp.js['data']))['unuseSceneList']
                    for scene in unuseSceneList:
                        if scene['sceneName'] not in ['室内', '户外', '餐厅', '马路', '定向聚焦']:
                            self.scene_id_list.append(scene['hearingAidSceneId'])
            except UnboundLocalError as JsonTypError:
                resp.failure(f'{JsonTypError}场景为空')
            except TypeError as nodata:
                resp.failure(f'场景为空:{nodata}')

        del_url = '/platformRetoneFit//api/hearingAidScene/needAppUserAuth/responseEncode/requestDecode/batchDeleteHearingAidScene'
        data = {
            'hearingAidSceneIdList': self.scene_id_list
        }
        # print(scene_id_list)
        with self.rest('post', del_url, data=enconde_bs64(data), headers=self.header) as resp:
            if resp.status_code != 200 or (resp.js['data'] is None and resp.js['description'] is not None):
                resp.failure(f"===错误返回status_code={resp.status_code}:resp_text={resp.js}===")
            else:
                resp.success()






class PushData(FastHttpUser):

    host = "https://www.retone-hearing.fit"
    wait_time = constant_pacing(2)
    abstract = True
    fake = faker.Faker()
    cookie = get_cookie()
    def on_start(self):
        numbers_of_user = False
        if numbers_of_user == True:
            self.header = {"Cookie": f"hearingaid_user={get_cookie()}",
                           "Content-Type": "application/json"}
        else:
            self.header = {"Cookie": f"hearingaid_user={self.cookie}",
                           "Content-Type": "application/json"}

    @task
    @tag('push')
    def push_data(self):
        # 本地场景数据同步到服务器
        sync_data_url = '/platformRetoneFit/api/hearingAidScene/needAppUserAuth/responseEncode/requestDecode/syncLocalHearingAidSceneToServer'
        data = {
            "programNumber": 0,
            "earType": "LEFT",
            "crDataMaps":  [
                    {
                        "0": 32,
                        "1": 32,
                        "2": 32,
                        "3": 32,
                        "4": 32,
                        "5": 32,
                        "6": 32,
                        "7": 32
                    },
                    {
                        "0": 32,
                        "1": 32,
                        "2": 32,
                        "3": 32,
                        "4": 32,
                        "5": 32,
                        "6": 32,
                        "7": 32
                    }
                ],
            "gainDataMap": {
                    "22": 0,
                    "23": 0,
                    "24": 0,
                    "25": 0,
                    "26": 0,
                    "27": 0,
                    "28": 0,
                    "29": 0,
                    "30": 0,
                    "31": 0,
                    "10": 0,
                    "11": 0,
                    "12": 0,
                    "13": 0,
                    "14": 0,
                    "15": 0,
                    "16": 0,
                    "17": 0,
                    "18": 0,
                    "19": 0,
                    "0": 0,
                    "1": 0,
                    "2": 0,
                    "3": 0,
                    "4": 0,
                    "5": 0,
                    "6": 0,
                    "7": 0,
                    "8": 0,
                    "9": 0,
                    "20": 0,
                    "21": 0
                },
            "mpoDataMap": {
                    "0": 157,
                    "1": 157,
                    "2": 157,
                    "3": 157,
                    "4": 157,
                    "5": 157,
                    "6": 157,
                    "7": 157
                }
            }
        with self.rest('post',sync_data_url, data=enconde_bs64(data), headers=self.header) as resp:
            if resp.status_code != 200 or (resp.js['data'] is None and resp.js['description'] is not None):
                resp.failure(f"===错误返回:{resp.js}===")
            else:
                resp.success()
        # 根据场景程序编号获取自助调节坐标点
        get_justment_url = '/platformRetoneFit/api/hearingAidScene/needAppUserAuth/responseEncode/requestDecode/getSelfAdjustmentPointInfo'
        data = {
            "programNumber": 0
        }
        with self.rest('post', get_justment_url, data=enconde_bs64(data), headers=self.header) as resp:
            if resp.status_code != 200 or (resp.js['data'] is None and resp.js['description'] is not None):
                resp.failure(f"===错误返回:{resp.js}===")
            else:
                resp.success()


    @task
    def push_hearing_data(self):
        # 将左右耳全部场景数据同步到服务端
        push_hearingaid_data = '/platformRetoneFit/api/hearingAidScene/needAppUserAuth/responseEncode/requestDecode/syncAllLocalHearingAidSceneToServer'
        data = {
            "sceneInfoList": [
                {
                    "programNumber": 0,
                    "earType": "LEFT",
                    "crDataMaps":[
                    {
                        "0": 32,
                        "1": 32,
                        "2": 32,
                        "3": 32,
                        "4": 32,
                        "5": 32,
                        "6": 32,
                        "7": 32
                    },
                    {
                        "0": 32,
                        "1": 32,
                        "2": 32,
                        "3": 32,
                        "4": 32,
                        "5": 32,
                        "6": 32,
                        "7": 32
                    }
                ],
            "gainDataMap": {
                    "22": 0,
                    "23": 0,
                    "24": 0,
                    "25": 0,
                    "26": 0,
                    "27": 0,
                    "28": 0,
                    "29": 0,
                    "30": 0,
                    "31": 0,
                    "10": 0,
                    "11": 0,
                    "12": 0,
                    "13": 0,
                    "14": 0,
                    "15": 0,
                    "16": 0,
                    "17": 0,
                    "18": 0,
                    "19": 0,
                    "0": 0,
                    "1": 0,
                    "2": 0,
                    "3": 0,
                    "4": 0,
                    "5": 0,
                    "6": 0,
                    "7": 0,
                    "8": 0,
                    "9": 0,
                    "20": 0,
                    "21": 0
                },
            "mpoDataMap": {
                    "0": 157,
                    "1": 157,
                    "2": 157,
                    "3": 157,
                    "4": 157,
                    "5": 157,
                    "6": 157,
                    "7": 157
                }
                }
            ]
        }
        with self.rest('post', push_hearingaid_data, data=enconde_bs64(data), headers=self.header) as resp:
            if resp.status_code != 200 or (resp.js['data'] is None and resp.js['description'] is not None):
                resp.failure(f"===错误返回:{resp.js}===")
            else:
                resp.success()



if __name__ == '__main__':
    # start_time = time.time()
    # get_cookie()
    # end_tiem = time.time()
    # t = end_tiem - start_time
    # print(f"t={t}")
    # fake=faker.Faker()
    # for i in range(10):
    #     print(fake.street_name())
    # run_single_user(PushData)
    run_single_user(HearingAidScene)

